import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import {getMenu} from "@/apis/global";
import {useMenuStore} from "@/stores/user";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: HomeView
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/LoginView.vue')
        }
    ]
})

export interface Menu {
    id: number;
    meta: {
        [k: string]: any
    };
    name: string;
    path: string;
    children: Menu[];
    parentId?: number;

    [k: string]: any;
}

export async function loadRoute() {
    const {data} = await getMenu();
    const menu: Menu[] = [];
    // 设置路由
    data.data.forEach(({name: routeName, meta, parentId, id}: Menu) => {
        const route: Menu = {
            id,
            meta,
            name: routeName,
            path: (parentId === 0 ? '/' : '') + routeName,
            component: () => import(`@/views/${routeName}View.vue`),
            children: [],
            parentId
        }
        // 如果有父级路由
        if (parentId !== 0) {
            const parentRoute = menu.find((r) => r.id === parentId) as Menu;
            router.addRoute(parentRoute.name, route);
            parentRoute.children.push(route);
        } else {
            router.addRoute('home', route);
            menu.push(route);
        }
    });
    // 设置菜单
    const menuStore = useMenuStore();
    menuStore.setMenu(menu);
    return data.check;
}

export default router
